package com.qianbao.qianbaobusiness.ui.cashier;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.androidbase.webview.WebViewTbsActivity;
import com.androidbase.widget.recycleadpter.BaseRecycleViewAdapter;
import com.baseandroid.config.Constant;
import com.baseandroid.config.Global;
import com.baseandroid.mvp.BaseMvpActivity;
import com.baseandroid.utils.FormatUtil;
import com.baseandroid.utils.TimeUtils;
import com.qianbao.qianbaobusiness.R;
import com.qianbao.qianbaobusiness.json.MerchantInfo;
import com.qianbao.qianbaobusiness.json.SettlementDetailBean;
import com.qianbao.qianbaobusiness.json.UnCheckedBean;
import com.qianbao.qianbaobusiness.ui.help.HelpCenterActivity;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

import static com.baseandroid.config.Api.balanceRuleUrl;
import static com.baseandroid.config.Api.balanceWayUrl;
import static java.lang.Double.parseDouble;

/**
 * 结算对账
 */
public class SettlementActivity extends BaseMvpActivity<SettlementView, SettlementPresenter>
        implements SettlementView, SwipeRefreshLayout.OnRefreshListener
                           , BaseRecycleViewAdapter.OnLoadMoreListener {
    @BindView(R.id.toolbar_back)
    RelativeLayout toolbarBack;    //返回

    @BindView(R.id.toolbar_title)
    TextView toolbarTitle;     //标题

    @BindView(R.id.right_text)
    TextView rightText;    //帮助中心

    @BindView(R.id.tv_rule_text)
    TextView tvRuleText;   //结算规则

    @BindView(R.id.tv_way_text)
    TextView tvWayText;    //对账方法

    @BindView(R.id.tv_search_text)
    TextView tvSearchText;   //历史账单

    @BindView(R.id.tv_prompt)
    TextView tvPrompt;     //提示

    @BindView(R.id.tv_settle_date)
    TextView tv_settle_date;   //未到账日期

    @BindView(R.id.rel_sel_data)
    RelativeLayout relSelData;

    @BindView(R.id.balance_count)
    TextView balanceCount;         //未结算文本

    @BindView(R.id.balance_right_arraw)
    ImageView balanceRightArraw;       //箭头

    @BindView(R.id.rel_to_jump)
    RelativeLayout relToJump;  //跳转到结算会送

    @BindView(R.id.tv_all_text)
    TextView tvAllText;    //结算汇总

    @BindView(R.id.swipe_all)
    SwipeRefreshLayout swipeAll;    //上拉刷新

    @BindView(R.id.recy_all)
    RecyclerView recyAll;
    /**
     * 变量相关
     */
    private int pageNum = 1;    //页码
    private String            startData;  //开始日期
    private String            endData;    //结束日期
    private SettlementAdapter adapter;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_settlement;
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void setupView() {
        toolbarTitle.setText(getApplicationContext().getResources().getString(R.string.settlement_add_reconciliation));
        rightText.setText(getApplicationContext().getResources().getString(R.string.help_center));
        rightText.setVisibility(View.VISIBLE);
        rightText.setTextColor(ContextCompat.getColor(this, R.color.text_support));
        getPresenter().queryDaysUnCheck(getSelectedPosMerchantNo());
    }

    private String getSelectedPosMerchantNo() {
        String posMerchantNos = "";
        List<MerchantInfo> merchantList = Global.getSelectedShopListInfo().merchantList;
        if (merchantList == null || merchantList.size() == 0) {
            return posMerchantNos;
        } else {
            for (MerchantInfo merchantInfo : merchantList) {
                if (merchantInfo.isSelected) {
                    if (TextUtils.isEmpty(posMerchantNos)) {
                        posMerchantNos = merchantInfo.posMerchantNo;
                    } else {
                        posMerchantNos = posMerchantNos + "," + merchantInfo.posMerchantNo;
                    }
                }
            }
            return posMerchantNos;
        }
    }

    @Override
    protected void setupData(Bundle savedInstanceState) {
        startData = TimeUtils.getDateNDaysDelay(-30, Constant.DATE_YYYYMMDD);
        endData = TimeUtils.getDateNDaysDelay(0, Constant.DATE_YYYYMMDD);
        adapter = new SettlementAdapter(this);
        recyAll.setLayoutManager(new LinearLayoutManager(this));
        swipeAll.setColorSchemeColors(ContextCompat.getColor(this, R.color.text_red));
        swipeAll.setOnRefreshListener(this);
        recyAll.setAdapter(adapter);
        adapter.setEmptyView(R.layout.cashier_empty_view);
        getPresenter().queryColtCheckedPage(getSelectedPosMerchantNo(), pageNum
                , 10, startData, endData);
    }

    @OnClick({R.id.toolbar_back, R.id.right_text, R.id.tv_rule_text, R.id.tv_way_text
            , R.id.tv_search_text, R.id.tv_all_text, R.id.rel_to_jump})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_back:
                finish();       //返回操作
                break;

            case R.id.right_text:  //帮助中心
                Intent intent = new Intent(this, HelpCenterActivity.class);
                intent.putExtra("sceneId", "2");
                startActivity(intent);
                break;

            case R.id.tv_rule_text:    //结算规则
                Intent intent1 = new Intent(this, WebViewTbsActivity.class);
                intent1.putExtra(WebViewTbsActivity.WEBVIEW_TITLE
                        , getApplicationContext().getResources().getString(R.string.balance_rule));
                intent1.putExtra(WebViewTbsActivity.WEBVIEW_URL, balanceRuleUrl);
                startActivity(intent1);
                break;

            case R.id.tv_way_text:    //对账方法
                Intent intent2 = new Intent(this, WebViewTbsActivity.class);
                intent2.putExtra(WebViewTbsActivity.WEBVIEW_TITLE
                        , getApplicationContext().getResources().getString(R.string.balance_way));
                intent2.putExtra(WebViewTbsActivity.WEBVIEW_URL, balanceWayUrl);
                startActivity(intent2);
                break;

            case R.id.tv_search_text:  //历史账单
                startActivity(new Intent(this, HistoryBalanceActivity.class));
                break;

            case R.id.rel_to_jump:     //结算汇总
                startActivity(new Intent(this, SummaryBalanceActivity.class));
                break;

            case R.id.tv_all_text:     //结算汇总
                startActivity(new Intent(this, SummaryBalanceActivity.class));
                break;
        }
    }

    /**
     * 请求未结算对象回调
     *
     * @param bean
     */
    @Override
    public void onSuccess(UnCheckedBean bean) {
        tvPrompt.setText("以下日期的收银，预计在下一个工作日"
                                 + TimeUtils.getDate(bean.getSettleDate(), Constant.DATE_YYYYMMDD, Constant.DATE_MMDD)
                                 + "(" + TimeUtils.DateToWeek(bean.getSettleDate(), Constant.DATE_YYYYMMDD) + ") 24点前到账");
        if (TextUtils.isEmpty(bean.getFestivalDay())) {
            tv_settle_date.setText(TimeUtils.getDate(bean.getChkAccountDate()
                    , Constant.DATE_YYYYMMDD, Constant.DATE_MMDD)
                                           + "(" + (TimeUtils.isToday(bean.getChkAccountDate(), Constant.DATE_YYYYMMDD) ? "今天," : "")
                                           + TimeUtils.DateToWeek(bean.getChkAccountDate(), Constant.DATE_YYYYMMDD) + ")");
        } else {
            tv_settle_date.setText(TimeUtils.getDate(bean.getChkAccountDate()
                    , Constant.DATE_YYYYMMDD, Constant.DATE_MMDD)
                                           + "(" + TimeUtils.DateToWeek(bean.getChkAccountDate(), Constant.DATE_YYYYMMDD)
                                           + "," + bean.getFestivalDay() + ")");
            relSelData.setVisibility(TextUtils.isEmpty(tv_settle_date.getText().toString())
                                             ? View.GONE : View.VISIBLE);
        }

        try {
            String v = parseDouble(bean.getSettlementAmtTotal()) / 100 + "";
            balanceRightArraw.setVisibility(View.VISIBLE);
            v = FormatUtil.getMoneyFormat(v);
            balanceCount.setText(getApplicationContext().getResources().getString(R.string.rmb) + v);
        } catch (Exception e) {
            balanceRightArraw.setVisibility(View.INVISIBLE);
            balanceCount.setText(bean.getSettlementAmtTotal());
        }
    }

    /**
     * 结算汇总详情
     *
     * @param bean
     */
    @Override
    public void onPageSuccess(SettlementDetailBean bean) {
        if (bean.getList().size() < Constant.DEFAULT_PAGE_SIZE) {
            adapter.setEnableLoadMore(false);
        }
        adapter.resetData(bean.getList());
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onComplete() {
        if (swipeAll.isRefreshing()) {
            swipeAll.setRefreshing(false);
        }
    }

    @Override
    public void getError(Throwable e) {

    }

    @Override
    public void onRefresh() {
        pageNum = 1;
        adapter.setEnableLoadMore(true);
        getPresenter().queryColtCheckedPage(getSelectedPosMerchantNo(), pageNum
                , Constant.DEFAULT_PAGE_SIZE, startData, endData);
    }

    @Override
    public void onLoadMore() {
        pageNum++;
        getPresenter().queryColtCheckedPage(getSelectedPosMerchantNo(), pageNum
                , Constant.DEFAULT_PAGE_SIZE, startData, endData);
    }
}
